<script setup>
import { onMounted, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router';
import { changePasswordApi } from '../../api/login'
let loginInfo = ref({ username: '', password: '', newPassword: '' })

let router = useRouter()

async function change() {

  // 验证两次密码
  if(loginInfo.value.newPassword === loginInfo.value.password) {
    let result;
    let info = JSON.parse(localStorage.getItem('loginUser'))
    // 验证登录用户名 和 localStorage用户名是否一致
    if(info.name === loginInfo.value.username) {
      result  = await changePasswordApi (info.username, loginInfo.value.newPassword)
    }else {
      ElMessage.error('用户名错误！')
    }
    if(result.code == 1) {
      ElMessage.success('修改成功！')
      router.push('/login')
    }else {
      ElMessage.error(result.msg)
    }
    }else {
      ElMessage.error('两次密码不一致！')
    }
  }

onMounted(() => {
  loginInfo.value.username = JSON.parse(localStorage.getItem('loginUser')).name
})

//取消
const clear = () => {
  loginInfo.value = ({ username: '', password: '', newPassword: '' })
  ElMessage.info('取消修改！')
  router.push('/index')

}


</script>

<template>
  <div id="container">
    <div class="login-form">
      <el-form label-width="100px">
        <p class="title">修改密码 【{{ loginInfo.username }}】</p>

        <el-form-item label="输入密码" prop="password">
          <el-input type="password" v-model="loginInfo.password" placeholder="请输入密码"></el-input>
        </el-form-item>

        <el-form-item label="确认密码" prop="newPassword">
          <el-input type="password" v-model="loginInfo.newPassword" placeholder="请输入密码"></el-input>
        </el-form-item>

        <el-form-item>
          <el-button class="button" type="primary" @click="change">保存</el-button>
          <el-button class="button" type="info" @click="clear">取消</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<style scoped>
#container {
  padding: 10%;
  height: 410px;
  background-image: url('../../assets/bg1.jpg');
  background-repeat: no-repeat;
  background-size: cover;
}

.login-form {
  max-width: 400px;
  padding: 50px;
  margin: 0 auto;
  border: 1px solid #e0e0e0;
  border-radius: 10px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
  background-color: white;
}

.title {
  font-size: 30px;
  font-family: '楷体';
  text-align: center;
  margin-bottom: 30px;
  font-weight: bold;
}

.button {
  margin-top: 30px;
  width: 120px;
}
</style>